/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tbgb.resourcemanager;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 *
 * @author LưuQuang
 */
public class BaseResourceManager implements ResourceManager
{
    private final Hashtable resources = new Hashtable();
    private final Hashtable loaders = new Hashtable();

    public Object getResource(Integer resourceKey, String resourceName)
    {
        ResourceLoader resourceLoader = (ResourceLoader) this.loaders.get(resourceKey);
        Hashtable resourceList = (Hashtable) this.resources.get(resourceKey);
        
        if (resourceLoader != null)
        {
            if (!resourceLoader.isReuseResource())
            {
                return resourceLoader.loadResource(resourceName);
            }
            else
            {
                if (resourceList == null)
                {
                    resourceList = new Hashtable();
                    this.resources.put(resourceKey, resourceList);
                }
                
                if (resourceList.containsKey(resourceName))
                {
                    return resourceList.get(resourceName);
                }
                else
                {
                    Object resource = resourceLoader.loadResource(resourceName);
//                    System.out.println("Resource: " + resourceName + "=" + resource);
                    if (resource != null)
                    {
                        resourceList.put(resourceName, resource);
                    }
                    
                    return resource;
                }
            }
        }
        
        return null;
    }

    public Object getResource(String resourceName)
    {
        Enumeration resourceLists = this.resources.elements();
        while (resourceLists.hasMoreElements())
        {
            Hashtable resourceList = (Hashtable) resourceLists.nextElement();
            if (resourceList != null && resourceList.containsKey(resourceName))
            {
                return resourceList.get(resourceName);
            }
        }

        return null;
    }

    public void addResourceLoader(ResourceLoader resourceLoader)
    {
        this.loaders.put(resourceLoader.getResourceKey(), resourceLoader);
        if (resourceLoader.isReuseResource())
        {
            this.resources.put(resourceLoader.getResourceKey(), new Hashtable());
        }

    }

    public void LoadResources()
    {
    }

    public void UnloadResources()
    {
    }
}